package com.ltxtiyu.video.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ltxtiyu.video.cacheDao.ConfigCacheDao;
import com.ltxtiyu.video.common.CodeTypeConstant;
import com.ltxtiyu.video.common.ConfigConstant;
import com.ltxtiyu.video.common.JsonTool;
import com.ltxtiyu.video.common.RetEnum;
import com.ltxtiyu.video.dao.ltx.AreaDao;
import com.ltxtiyu.video.entity.Area;
import com.ltxtiyu.video.service.app.OtherService;
import com.ltxtiyu.video.tool.HttpTool;
import com.ltxtiyu.video.tool.ObjectTool;
import com.ltxtiyu.video.tool.StringTool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OtherServiceImpl implements OtherService {
    public static final Logger LOGGER = LoggerFactory.getLogger(OtherServiceImpl.class);
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    AmqpTemplate amqpTemplate;

    @Autowired
    ConfigCacheDao configCacheDao;
    @Autowired
    AreaDao areaDao;
    /**
     * 根据关键字搜索周边位置
     * 调用高德地图api
     *
     * @param params
     * @return
     */
    @Override
    public String placeText(Map<String, String> params) {
        String url = configCacheDao.selectByCkey(ConfigConstant.AMAP_URL_PLACE_TEXT).getCvalue();
        String key = configCacheDao.selectByCkey(ConfigConstant.AMAP_KEY).getCvalue();
        StringBuffer sb = new StringBuffer();
        for(String pKey:params.keySet()){
            sb.append(pKey).append("=").append(params.get(pKey)).append("&");
        }
        String requestParams = sb.append("key").append("=").append(key).toString();
        String finalUrl = url+requestParams;
        return HttpTool.doGet(finalUrl);
    }

    /**
     * 根据经纬度搜索周边
     * @param params
     * @return
     */
    @Override
    public String placeAround(Map<String, String> params) {
        String url = configCacheDao.selectByCkey(ConfigConstant.AMAP_URL_PLACE_AROUND).getCvalue();
        String key = configCacheDao.selectByCkey(ConfigConstant.AMAP_KEY).getCvalue();
        StringBuffer sb = new StringBuffer();
        for(String pKey:params.keySet()){
            sb.append(pKey).append("=").append(params.get(pKey)).append("&");
        }
        String requestParams = sb.append("key").append("=").append(key).toString();
        String finalUrl = url+requestParams;
        return HttpTool.doGet(finalUrl);
    }

    /**
     * 查询所有地区记录
     * @return
     */
    @Override
    public String listArea() {
        List<Area> areas = areaDao.selectAll();
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> areaList = new ArrayList<>();
        for(Area area:areas){
            Map<String, Object> resultArea = new HashMap<>();
            resultArea.put("id",area.getId());
            resultArea.put("name",area.getName());
            resultArea.put("nid",area.getNid());
            resultArea.put("pid",area.getPid());
            resultArea.put("domain",area.getDomain());
            areaList.add(resultArea);
        }
        result.put("areaList",areaList);
        result.put("version","v1.0");

        return JsonTool.genJson(RetEnum.SUCCESS,result);
    }

    /**
     * 收集收据
     * @param params
     * @return
     */
    @Override
    public String statisticsCollect(Map<String, String> params) {
        String dataPacket = ObjectTool.stringOrNull(params.get("dataPacket"));

        Integer userId = -1;
        JSONArray listJsonArray = null;
        try {
            JSONObject packetJson = JSON.parseObject(dataPacket);
            listJsonArray = packetJson.getJSONArray("list");
            userId = packetJson.getInteger("user_id");
        }catch (Exception e){
            LOGGER.error(">>>>>>>>>>>>>收集数据发生错误 - 解析json, 请求参数:{}, 错误信息:{}", dataPacket, e);
        }
        if(listJsonArray == null){  // json格式不正确
            return JsonTool.genJson(RetEnum.REQUEST_PARAM_ERROR);
        }
        for(int i = 0 ; i < listJsonArray.size(); i++){
            JSONObject jsonObject = listJsonArray.getJSONObject(i);
            JSONObject data = jsonObject.getJSONObject("data");
            try{
                Integer type = jsonObject.getInteger("type");
                if(type.equals(CodeTypeConstant.STATISTICS_COLLECT_MOMENT_TYPE_1100)){  // 播放次数
                    Integer playTimes = data.getInteger("play_times");  // 播放次数
                    Integer momentId = data.getInteger("id");       // 动态id
                    if(playTimes.intValue() > 0){
                        // 修改redis缓存的统计信息,播放量
                        try{
                            String momentJson = (String) stringRedisTemplate.opsForHash().get(ConfigConstant.REDIS_MOMENT_HASH_PREFIX, momentId + "");
                            if(StringUtils.isNotBlank(momentJson)){
                                Map<String, String> redisMomentMap = (Map<String, String>) JSON.parse(momentJson);
                                Integer viewCount = Integer.parseInt(redisMomentMap.get(ConfigConstant.REDIS_MOMENT_MAP_KEY_VIEW_NOW));
                                Integer finalViewCount = new Integer(playTimes.intValue() + viewCount.intValue());
                                redisMomentMap.put(ConfigConstant.REDIS_MOMENT_MAP_KEY_VIEW_NOW,finalViewCount+"");
                                stringRedisTemplate.opsForHash().put(ConfigConstant.REDIS_MOMENT_HASH_PREFIX, momentId + "", JSON.toJSONString(redisMomentMap));
                            }
                        }catch (Exception e){
                            LOGGER.info(">>>>>>>>>>>>>>>>>>修改redis播放数失败,momentId:{}",momentId);
                        }
                    }

                }else if(type.equals(CodeTypeConstant.STATISTICS_COLLECT_MOMENT_TYPE_1101)){    // 完播次数
                    if(userId.intValue() > 0){
                        Map<String, Object> messageMap = new HashMap<>();
                        messageMap.put("user_id",userId);
                        messageMap.put("moment_id",data.getInteger("id"));
                        messageMap.put("full_play_times",data.getInteger("full_play_times"));
                        messageMap.put("play_date", StringTool.stringToDate(data.getString("play_date")));
                        amqpTemplate.convertAndSend(ConfigConstant.MESSAGE_NAME_MOMENT_ADD_PLAY_TIMES,messageMap);
                        LOGGER.info(">>>>>>>>>>>>>>>添加视频完播次数消息发出队列, 参数:{}", params.toString());
                    }
                }
            }catch (Exception e){
                LOGGER.error(">>>>>>>>>>>>>收集数据发生错误 - 收集, 请求参数:{}, 错误信息:{}", jsonObject.toJSONString(), e);
            }
        }
        return JsonTool.genJson(RetEnum.SUCCESS);
    }
}
